<script setup lang="ts">
import { onHide, onLaunch, onShow } from '@dcloudio/uni-app'
import { judgePlatform } from './utils/platform'
import { CURRENT_PLATFORM, PLATFORMS } from './enums/platformEnum'
import { HideLoading, Loading, Modal } from './utils/uniapi/prompt'
import { useUserStore } from '@/state/modules/user'
import { useAuthStore } from '@/state/modules/auth'
import { removeInterceptor, setupInterceptors } from '@/utils/interceptors'
import { useRouterStore } from '@/state/modules/router'

const platform = CURRENT_PLATFORM
const isVue3 = judgePlatform(PLATFORMS.VUE3)
const apiUrl = import.meta.env.VITE_BASE_URL

// #ifdef MP-WEIXIN

/**
 * 小程序使用的更新
 */
const mpUpdate = () => {
  // 版本更新管理器对象： updateManager，用于管理小程序更新
  const updateManager = uni.getUpdateManager()
  // 分享到朋友圈时，updateManager 为 null
  if (!updateManager)
    return

  // 请求完新版本信息时回调
  updateManager?.onCheckForUpdate((res) => {
    console.log('检测小程序更新...', res)
    if (!res?.hasUpdate)
      return
    Loading('更新中…')
  })

  // 新版本下载完成时回调
  updateManager?.onUpdateReady((_res) => {
    HideLoading()
    updateManager.applyUpdate()
  })

  // 新版本下载失败时回调
  updateManager?.onUpdateFailed((res) => {
    console.log('onUpdateFailed', res)
    HideLoading()
    Modal({
      title: '升级失败',
      content: '新版本下载失败，请检查网络！',
      showCancel: false,
    })
  })
}

// #endif

onLaunch(() => {
  // #ifdef MP-WEIXIN
  console.log(
    `\n%cUNIAPP%c${platform}%cVUE%c${isVue3 ? '3' : '2'}%cAPI%c${apiUrl}%c\n`,
    'background:#2b993a;color:#fff;padding:3px 6px;border-radius:4px 0 0 4px;',
    'background:#fff;padding:3px 6px;color:#000;margin-right:1em;border-radius:0 4px 4px 0;',
    'background:#42d392;color:#fff;padding:3px 6px;border-radius:4px 0 0 4px;',
    'background:#fff;padding:3px 6px;color:#000;margin-right:1em;border-radius:0 4px 4px 0;',
    'background:orange;color:#fff;padding:3px 6px;border-radius:4px 0 0 4px;',
    'background:#fff;padding:3px 6px;color:#000;margin-right:1em;border-radius:0 4px 4px 0;',
    '',
  )
  // #endif

  removeInterceptor()
  setupInterceptors()
  const appStore = useRouterStore()
  appStore.initialize()
})

onShow(() => {
  const authStore = useAuthStore()
  authStore.initToken()
  const userStore = useUserStore()
  userStore.initUserInfo()

  // #ifdef MP-WEIXIN
  mpUpdate()
// #endif
})

onHide(() => {
  // console.log('App Hide')
})
</script>

<style lang="scss">
/* #ifdef APP-NVUE */
@import "./tmui/scss/nvue.css";
/* #endif */
/* #ifndef APP-NVUE */
@import "./tmui/scss/noNvue.css";
/* #endif */

@import "@/assets/main.scss";
</style>
